<?php
/**
 * 系统站点/地区（基础）
 * (model)
 */

namespace App\Models\Basics;

use App\Models\OverSeasBa\Warehouse;
use Illuminate\Database\Eloquent\Model;
class SysArea extends Model
{
    protected $table = 'b_sys_area';

    public $timestamps = false;

    protected $guarded = [];

    const STATUS_YES = 1; //启用
    const STATUS_NO  = 2; //停用

    const AREA_EU = 4; //EU站点ID
    const AREA_JP = 6; //JP站点ID

    public function warehouse(){
        return $this->hasMany(Warehouse::class, 'area_id', 'id');
    }

    public static function options(){
        return self::query()->pluck('area','id');
    }

    public static function options1(){
        return self::query()->pluck('area_cn','id');
    }

    //销售报表查看权限
    //欧洲站
    public static $_EUArea = ['EU','UK','AE'];//可查看站点
    public static $_EUCountry = ['UK','DE','ES','FR','IT','PL','NL','SE','TR','AE','BE'];//可查看国家
    //北美站
    public static $_NAArea = ['US','CA','MX','BR','AU','AE'];//可查看站点
    public static $_NACountry = ['US','CA','MX','BR','AU','AE'];//可查看国家
    //日本站
    public static $_JPArea = ['JP','AE'];//可查看站点
    public static $_JPCountry = ['JP','AE'];//可查看国家
    //Payment报表账号处理
    //欧洲站
    public static $_EUCountryForAccount = ['UK','DE','ES','FR','IT','PL','NL','SE','TR','BE'];
    //北美站
    public static $_NACountryForAccount = ['US','CA','MX','BR'];
    /**
     * 获取站点ID
     * @param string $area
     * @return int
     */
    public static function getSysAreaIdByArea($area = 'PUBLIC'){
        $areaId = self::query()->where('area',$area)->value('id');
        return $areaId ?: 0;
    }

    /**
     * 获取站外站点ID
     * @return int
     */
    public static function getSysOutAreaIdByArea(){
        $areaId = self::query()->where('area','OUT')->value('id');
        return $areaId ?: 0;
    }

    public static function getSysAreaById($id){
        $area = self::query()->where('id',$id)->value('area');
        return $area ?: '';
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            $count = SysIArea::query()->where('area_id',$model->id)->count();
            if($count > 0){
                throw new \Exception('使用中勿删除');
            }
            $count = SysLArea::query()->where('country_id',$model->id)->count();
            if($count > 0){
                throw new \Exception('使用中勿删除');
            }
        });
    }
}
